#include "reader.h"


reader::reader()
{
}

reader::reader(char *binFile, char *dbFile)
{
	openFile(binFile);
	getSimHours();
	sDriver = "MICROSOFT ACCESS DRIVER (*.mdb)";
	sFile = dbFile;
	sDsn.Format("ODBC;DRIVER={%s};DSN='';DBQ=%s",sDriver,sFile);
	db.Open(NULL,false,false,sDsn);
	printf ("Connect %s succeeded.\n", dbFile);
	CString saveAllBinSetting;
	try
	{
		CRecordset rs(&db);
		rs.Open(CRecordset::forwardOnly, _T(SAVE_BIN_ALL_SQL));
		rs.GetFieldValue("VALUE", saveAllBinSetting);
		rs.Close();
		saveBinAll = atoi(saveAllBinSetting);
	}
	catch (CDBException *p)
	{
		printf("%s\n", p->m_strError);
	}
}

BOOL reader::openFile (char *fileName)
{
	file_Handle = open(fileName, O_BINARY);
	if (file_Handle >0) 
	{
		printf ("Open %s succeeded.\n", fileName);
		return true;
	}
	else 
	{
		printf ("Failed Open %s.\n", fileName);
		switch (errno) 
		{
			case EACCES:  printf ("Permission denied.\n"); break;
			case EMFILE:  printf ("No file handle available.\n"); break;
			case ENOENT:  printf ("File or path not found.\n"); break;
			default:      printf ("Unknown error.\n"); break;
		}
	}

	return false;
}

BOOL reader::closeFile()
{
	if (close (file_Handle) == 0)
	{
		printf ("Close file succeeded.\n");
		return true;
	}
	else 
	{
		printf ("Close file failed.\n");
		switch (errno) 
		{
			case EBADF:  printf ("File not open.\n"); break;
			default:     printf ("Unknown error.\n"); break;
		}
	}

	return false;

}


int reader::getSimHours ()
{
	readDateInfo();

	System::DateTime dateStart = System::DateTime (getSimStartYear(), getSimStartMonth(), getSimStartDay(), 0, 0, 0);

	System::DateTime dateEnd = System::DateTime (getSimEndYear(), getSimEndMonth(), getSimEndDay(),	0, 0, 0);

	System::TimeSpan diff = dateEnd - dateStart;

	simHours = diff.Days * 24 + 24;

	return simHours;

}


void reader::readDateInfo()
{
	lseek(file_Handle, HRCOMHEADER_OFFSET, SEEK_SET);
	read(file_Handle, &date, HRCOMHEADER_SIZE);

}

/*
 * return float value from binary file with given offset value
 */
float reader::get_offset_value(unsigned long offset)
{
	if (offset == -1)
		return -1;
	float value = 0;
	lseek(file_Handle, offset, SEEK_SET);
	read(file_Handle, &value, sizeof(float));
	return value;
}


reader::~reader ()
{
	if (file_Handle >0) 
		closeFile();
	if (!sFile.IsEmpty() )
	{
		db.Close();
		printf("Disconnnect from MDB\n");
	}
}